/**
 * 分页工具类
 * @author liangst
 */
package com.jf.cloud.service.sysmanager.common.taglib;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import org.apache.commons.codec.digest.DigestUtils;
import org.apache.commons.lang.StringUtils;

import com.jf.cloud.service.sysmanager.common.db.Condition;
import com.jf.cloud.service.sysmanager.common.db.Query;
import com.jf.cloud.service.sysmanager.common.db.SqlParse;
import com.jf.cloud.service.sysmanager.common.util.JsonUtil;

/**
 * @类功能说明：数据库分页工具类
 */
public class Paging<T> implements Serializable { 
	private static final long serialVersionUID = 1;
	// --- 排序的参数 Start ---
	public static final String ASC = "ASC"; // 排序 : 升序
	public static final String DESC = "DESC"; // 排序 : 降序
	// --- 排序的参数 End ---

	public static final String CURRENT_PAGE = "CURRENTPAGE"; // 当前页数
	public static final String PAGE_SIZE = "PAGESIZE"; // 页数
	public static final String TOTAL_ROWS = "TOTAL_ROWS"; // 总记录数
	public static final int DEFAULT_PAGE_SIZE = 10;
	// WhereMap 接受页面传递的参数
	protected Wm<String, Object> wm = new Wm<String, Object>();
	// 组装完 sql 后的参数 集合
	protected List<Object> param = new ArrayList<Object>();
	/**
	 * 是否要求分页;false 就不分页;true 就分页;默认是分页的
	 */
	private boolean isPaging = true; // 是否要求分页，如果设置为 false 就不分页，true 就分页，默认是分页的
	/**
	 * 查询对象
	 */
	private Query query;
	/**
	 * 是否需要查询出数据;
	 *   false 就不需要;
	 *   true 为需要;
	 *   默认是需要的
	 */
	private boolean selectDataList = true; // 是否需要查询出数据，如果设置为 false 就不需要，true 为需要，默认是需要的

	private int totalRows; // 总条数
	private int curPage; // 当前页数
	private int pageSize; // 每页大小
	private int gotopage; // 要去的页面 

	private int maxPage; // 最大页数
	private int startRowIdx; // 开始值
	private int endRowIdx; // 结束值

	private List<T> dataList; // 数据集

	private String message; // 简单的消息传递
	private String others; // 其他信息
	private String orderBy=""; // 排序字符串
	private String sumFeeSx; //收获订单采购手续费支出合计
	
	public String getSumFeeSx() {
		return sumFeeSx;
	}
	public void setSumFeeSx(String sumFeeSx) {
		this.sumFeeSx = sumFeeSx;
	}
	/**
	 * 增加特殊条件
	 */
	public Condition put(String columnName, Object value) {
		value = value == null ? "" : value;
		return getQuery().put(columnName, value);
	}
    /**
     * 得到 查询的 sql 语句
     * 不包含 where 之前的语句
     */
	public String getWhereSQL() {
		param = new ArrayList<Object>();
		String sql= SqlParse.parse(wm, param, createQuery());
		if(sql!=null && sql.startsWith(" AND")){
			sql =" "+sql.substring(4,sql.length());
		}
		return sql;
	}
	/**
	 * 得到 查询的 sql 语句
	 * 不包含 where 之前的语句
	 */
	public String getAndSQL() {
		param = new ArrayList<Object>();
		String sql= SqlParse.parse(wm, param, createQuery());
		return sql;
	}
	/**
	 * 得到 查询的 sql 语句 
	 * 不包含 where 之前的语句
	 * needWhere : 是否需要带 where 字符
	 */
	public String getWhereSQL(boolean needWhere) { 
		String sqlString = getWhereSQL();
		if(needWhere){
			if(sqlString!=null && sqlString.length()>3){
				sqlString = " WHERE "+sqlString;
			}
		}
		return sqlString;
	}
	 /**
     * 得到 查询的 参数
     */
	public List<Object> getParamList() {
		return param;
	}
    /**
     * 移除 wm 范围内 参数 如果不存或者 值为 null “”
     */
    public void removeParam(String... paramNames) {
    	if(paramNames!=null && paramNames.length>0){
    		for (int i = 0; i < paramNames.length; i++) {
				if(wm.containsKey(paramNames[i])){
					wm.remove(paramNames[i]);
				}
			}
    	}
    }
	/**
	 * 增加特殊条件 对于 wm(WhereMap) 已经存在的值
	 */
	public Condition put(String columnName) {
		return getQuery().put(columnName);
	}

	public Paging() {
		this(0, 1, DEFAULT_PAGE_SIZE);
	}

	public Paging(int total) {
		this(total, 1, DEFAULT_PAGE_SIZE);
	}

	public Paging(int total, int page) {
		this(total, page, DEFAULT_PAGE_SIZE);
	}

	public Paging(int total, int page, int size) {
		totalRows = total;
		curPage = page;
		pageSize = size;

		calculate();
	}

	private void calculate() {
		if (pageSize < 1) {
			pageSize = DEFAULT_PAGE_SIZE;
		}

		// cal the max page
		maxPage = totalRows / pageSize;
		if (totalRows % pageSize > 0) {
			maxPage++;
		}

		// cal the current page num
		if (curPage > maxPage) {
			curPage = maxPage;
		}
		if (curPage < 1) {
			curPage = 1;
		}
		if (maxPage < 1) {
			maxPage = 1;
		}

		// cal the start and end row idx
		startRowIdx = pageSize * (curPage - 1);
		endRowIdx = pageSize * curPage - 1;
		if (endRowIdx > totalRows - 1) {
			endRowIdx = totalRows - 1;
		}
	}

	public List<T> getDataList() {
		return dataList;
	}

	public void setDataList(List<T> dataList) {
		this.dataList = dataList;
	}

	// 得到分页的 字符串
	public String getLimitStr() {
		if (this.totalRows > 0) {
			calculate();
		}
		// 总数 >= 每页数量 LIMIT 每页数量，否则 LIMIT 总数  默认为10条
		int limitNum = this.totalRows >= this.pageSize ? this.pageSize : this.totalRows;
		if (this.gotopage <= 1) {
			this.curPage = 1;
			limitNum = limitNum==0?DEFAULT_PAGE_SIZE:limitNum;
			return " LIMIT " + limitNum;
		} else {
			if (this.gotopage >= this.maxPage) { // 超出页数
				this.curPage = maxPage;
				return " LIMIT " + (this.maxPage - 1) * this.pageSize + "," + limitNum;
			} else {
				this.curPage = gotopage;
				return " LIMIT " + (this.gotopage - 1) * this.pageSize + "," + limitNum;
			}
		}

	}

	public String getMessage() {
		return message;
	}

	public void setMessage(String message) {
		this.message = message;
	}

	public String getOthers() {
		return others == null ? " " : others;
	}

	public void setOthers(String others) {
		this.others = others;
	}

	public int getGotopage() {
		return gotopage;
	}

	public void setGotopage(int gotopage) {
		if (gotopage <= 1) {
			this.curPage = 1;
			gotopage = 1;
		} else {
			this.curPage = gotopage;
		}
		this.gotopage = gotopage;
	}

	public void setMaxPage(int maxPage) {
		this.maxPage = maxPage;
	}

	@Override
	public String toString() {
		return JsonUtil.toJSON(this);
	}

	public String getOrderBy() {
		if(StringUtils.isNotEmpty(orderBy)){
			SqlParse.isRisk(orderBy); 
		}
		return " "+orderBy;
	}

	public void setOrderBy(String orderBy) {
		this.orderBy = orderBy;
	}
    /**
     * 初始化 查询
     */
	public Query createQuery() {
		query= query == null ? new Query() : query;
		return query;
	}

	public Query getQuery() {
		query= query == null ? new Query() : query;
		return query;
	}

	public void setQuery(Query query) {
		this.query = query;
	}

	/**
	* 判断是否分页，默认是需要分页的
	* 
	* @return true 为分页，false 为不分页
	*/
	public boolean isPaging() {
		return isPaging;
	}

	/**
	 * 设置是否要分页显示
	 * 
	 * @param isPaging
	 */
	public void setPaging(boolean isPaging) {
		this.isPaging = isPaging;
	}

	/**
	 * 判断是否需要查询出数据
	 * 
	 * @return
	 */
	public boolean isSelectDataList() {
		return selectDataList;
	}

	/**
	 * 设置是否需要查询出数据
	 * 
	 * @param selectDataList
	 */
	public void setSelectDataList(boolean selectDataList) {
		this.selectDataList = selectDataList;
	}

	public void setTotalRows(int total) {
		totalRows = total;
		calculate();
	}

	public void setCurPage(int page) {
		curPage = page;
//        calculate();
	}

	public void setPageSize(int size) {
		pageSize = size;
//        calculate();
	}

	public int getEndRowIdx() {
		return endRowIdx;
	}

	public int getStartRowIdx() {
		return startRowIdx;
	}

	public int getMaxPage() {
		return maxPage;
	}

	public int getPageSize() {
		return pageSize;
	}

	public int getCurPage() {
		return curPage;
	}

	public int getTotalRows() {
		return totalRows;
	}

	public boolean hasNextPage() {
		return curPage < maxPage;
	}

	public boolean isFirstPage() {
		return curPage == 1;
	}

	public boolean isLastPage() {
		return curPage == maxPage;
	}

	public int getDEFAULT_PAGE_SIZE() {
		return DEFAULT_PAGE_SIZE;
	}

    
	public Map<String, Object> getWm() {
		return wm;
	}
	public void setWm(Wm<String, Object> wm) { 
		this.wm = wm;
	}
	public List<Object> getParam() {
		return param;
	}
	public void setParam(List<Object> param) {
		this.param = param;
	}
	/**
	 * 主要用于 作为缓存 key
	 * 压缩 字符串 方便更新使用 无其他用途
	 */
	public String cacheKey() {
		String key ="";
		if(this!=null){
			key = JsonUtil.toJSON(this);
			key = DigestUtils.md5Hex(key);
		}
		return key;
	}
	
	
}
